﻿using System.Data.Common;
using System.Data.SqlClient;

namespace PengSW.DbTools
{
    public static class DbTools
    {
        public static bool IsQueryHasResult(this DbConnection aConnection, string aSql)
        {
            using (DbCommand aSqlCommand = aConnection.CreateCommand())
            {
                aSqlCommand.CommandText = aSql;
                using (System.Data.Common.DbDataReader aSqlDataReader = aSqlCommand.ExecuteReader())
                {
                    bool aResult = aSqlDataReader.Read() && !aSqlDataReader.IsDBNull(0);
                    aSqlDataReader.Close();
                    return aResult;
                }
            }
        }

        public static bool IsDatabaseExist(this SqlConnection aConnection, string aDatabase)
        {
            return IsQueryHasResult(aConnection, string.Format("SELECT DB_ID('{0}')", aDatabase));
        }

        public static int RunSql(this DbConnection aConnection, string aSql, bool aThrowException = true)
        {
            try
            {
                using (DbCommand aSqlCommand = aConnection.CreateCommand())
                {
                    aSqlCommand.CommandText = aSql;
                    return aSqlCommand.ExecuteNonQuery();
                }
            }
            catch
            {
                if (aThrowException) throw;
                return 0;
            }
        }

        public static void CreateDatabase(this DbConnection aConnection, string aDatabase)
        {
            aConnection.RunSql(string.Format("CREATE DATABASE {0}", aDatabase));
        }

        public static void DropDatabase(this DbConnection aConnection, string aDatabase)
        {
            aConnection.RunSql(string.Format("DROP DATABASE {0}", aDatabase));
        }
    }
}
